document.addEventListener('DOMContentLoaded', function() {
  const getCookieBtn = document.getElementById('getCookie');
  const syncFansBtn = document.getElementById('syncFans');
  const cookieInput = document.getElementById('cookie');
  const appidInput = document.getElementById('appid');
  const statusDiv = document.getElementById('status');
  const logArea = document.getElementById('log');

  // 从storage加载保存的数据
  chrome.storage.local.get(['cookie', 'appid'], function(result) {
    if (result.cookie) cookieInput.value = result.cookie;
    if (result.appid) appidInput.value = result.appid;
  });

  // 添加日志函数
  function log(message, type = 'info') {
    const timestamp = new Date().toLocaleTimeString();
    const prefix = type === 'error' ? '❌ ' : type === 'success' ? '✅ ' : 'ℹ️ ';
    const logMessage = `[${timestamp}] ${prefix}${message}\n`;
    logArea.value += logMessage;
    logArea.scrollTop = logArea.scrollHeight;
    console.log(message);
  }

  // 清除日志
  function clearLog() {
    logArea.value = '';
  }

  // 获取Cookie按钮点击事件
  getCookieBtn.addEventListener('click', async function() {
    try {
      clearLog();
      log('开始获取Cookie...');
      
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      if (!tab.url.includes('mp.weixin.qq.com')) {
        throw new Error('请在微信公众号后台页面使用此插件');
      }

      const url = new URL(tab.url);
      const token = url.searchParams.get('token') || '';
      log(`获取到token: ${token}`);

      const cookies = await chrome.cookies.getAll({ url: 'https://mp.weixin.qq.com' });
      const cookieStr = cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');
      
      cookieInput.value = cookieStr;
      chrome.storage.local.set({ 
        cookie: cookieStr,
        token: token
      });

      log('Cookie获取成功！', 'success');
      showStatus('Cookie获取成功！', 'success');
    } catch (error) {
      log(`获取Cookie失败: ${error.message}`, 'error');
      showStatus('获取Cookie失败：' + error.message, 'error');
    }
  });

  // 同步粉丝按钮点击事件
  syncFansBtn.addEventListener('click', async function() {
    try {
      clearLog();
      const cookie = cookieInput.value;
      const appid = appidInput.value;

      if (!cookie || !appid) {
        throw new Error('Cookie和AppID不能为空！');
      }

      chrome.storage.local.set({ appid });
      log(`使用AppID: ${appid}`);

      const { token } = await chrome.storage.local.get(['token']);
      if (!token) {
        throw new Error('请先获取Cookie以获取token！');
      }
      log(`使用token: ${token}`);

      let offset = 0;
      let begin_openid = '';
      let totalSynced = 0;
      
      while (true) {
        const random = Math.random();
        const begin_create_time = Math.floor(Date.now() / 1000);
        
        // 构建完整的URL
        const url = `https://mp.weixin.qq.com/cgi-bin/user_tag?action=get_user_list&groupid=-2&begin_openid=${begin_openid}&begin_create_time=${begin_create_time}&limit=20&offset=${offset}&backfoward=1&token=${token}&lang=zh_CN&f=json&ajax=1&random=${random}`;
        
        log(`请求第${offset/20 + 1}页粉丝列表...`);

        const response = await fetch(url, {
          headers: {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': cookie,
            'Referer': `https://mp.weixin.qq.com/cgi-bin/user_tag?action=get_all_data&lang=zh_CN&token=${token}`,
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'X-Requested-With': 'XMLHttpRequest',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36'
          }
        });

        const data = await response.json();
        log(`获取到第${offset/20 + 1}页数据`);

        // 检查错误码
        if (data.base_resp) {
          if (data.base_resp.ret !== 0) {
            throw new Error(`API错误: ${data.base_resp.err_msg || '未知错误'}`);
          }
        }

        // 获取用户列表
        const userList = data.user_list?.user_info_list || [];
        if (userList.length === 0) {
          break;
        }

        // 处理用户数据
        const pageFans = [];
        for (const user of userList) {
          try {
            log(`处理用户: ${user.user_name}`);
            pageFans.push({
              nickname: user.user_name || '未知昵称',
              openid: user.user_openid,
              appid: appid,
              status: '1',
              photo: user.user_head_img || '',
              country: '',
              province: '',
              city: '',
              unionid: '',
              tag: user.user_group_id ? JSON.stringify(user.user_group_id) : ''
            });
          } catch (error) {
            log(`处理用户数据失败: ${error.message}`, 'error');
          }
        }

        // 同步当前页的粉丝数据
        if (pageFans.length > 0) {
          log(`同步第${offset/20 + 1}页的${pageFans.length}个粉丝...`);
          
          try {
            const saveResponse = await fetch('http://localhost:3000/api/saveFans', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                data: JSON.stringify(pageFans)
              })
            });

            const result = await saveResponse.json();
            if (result.success) {
              totalSynced += pageFans.length;
              log(`第${offset/20 + 1}页同步成功，当前已同步${totalSynced}个粉丝`, 'success');
            } else {
              throw new Error(result.message || '保存失败');
            }
          } catch (error) {
            log(`同步第${offset/20 + 1}页失败: ${error.message}`, 'error');
            // 继续下一页，不中断整个同步过程
          }
        }

        // 更新begin_openid为最后一个用户的openid
        if (userList.length > 0) {
          begin_openid = userList[userList.length - 1].user_openid;
        }
        
        offset += userList.length;

        // 添加延时，避免请求过快
        await new Promise(resolve => setTimeout(resolve, 1000));

        // 如果返回的用户数少于20，说明已经到最后一页
        if (userList.length < 20) {
          break;
        }
      }

      if (totalSynced > 0) {
        log(`同步完成！共同步${totalSynced}个粉丝`, 'success');
        showStatus(`同步完成！共同步${totalSynced}个粉丝`, 'success');
      } else {
        log('没有找到粉丝数据', 'error');
        showStatus('没有找到粉丝数据', 'error');
      }
    } catch (error) {
      log(`同步失败: ${error.message}`, 'error');
      showStatus('同步失败：' + error.message, 'error');
    }
  });

  // 显示状态信息
  function showStatus(message, type) {
    statusDiv.textContent = message;
    statusDiv.className = `status ${type}`;
  }
}); 